﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace XmlTools {
    public partial class XmlSourceSelect : UserControl {
        public XmlSourceSelect() {
            InitializeComponent();
        }

        private void _sourceFileNameBrowse_Click(object sender, EventArgs e) {
            DialogResult results = _sourceOpenFileDialog.ShowDialog(this);
            if (results == DialogResult.OK) {
                _sourceSelectFileName.Checked = true;
                _sourceFileName.Text = _sourceOpenFileDialog.FileName;
                _sourceFileName.Select();
            }
        }

        public byte[] XmlData {
            get {
                byte[] xml;
                if (_sourceSelectFileName.Checked) {
                    xml = File.ReadAllBytes(_sourceFileName.Text);
                }
                else {
                    xml = Encoding.Default.GetBytes((string) _sourceXml.Text);
                }

                return xml;
            }
        }

        public XmlDocument XmlDocument {
            get {
                byte[] xml = XmlData;

                using (Stream xmlStream = new MemoryStream(xml)) {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(xmlStream);
                    return doc;
                }
            }
        }

        private void _sourceFileName_Enter(object sender, EventArgs e) {
            _sourceSelectFileName.Checked = true;
        }

        private void _sourceXml_Enter(object sender, EventArgs e) {
            _sourceSelectXml.Checked = true;
        }

        public void AddTextToDropDown() {
            if (_sourceSelectFileName.Checked) {
                string text = _sourceFileName.Text;
                _sourceFileName.Items.Remove(text);
                _sourceFileName.Items.Insert(0, text);
                _sourceFileName.Text = text;
            }
        }

        public void SetXmlText(string xml) {
            _sourceXml.Text = xml;
        }
    }
}